package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JWTUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class loginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SystemUserService service;

    @Override
    public CaptchaVo getCaptcha() {
        //获取验证码尺寸及长度
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        //将验证码图形化
        String img = specCaptcha.toBase64();
        //获取验证码数据
        String verCode = specCaptcha.text().toLowerCase();
        //随机生成验证码的key
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        //将验证码信息存入redis中120秒
        redisTemplate.opsForValue().set(key, verCode, 120, TimeUnit.SECONDS);
        //将验证码信息保存在CaptchaVo对象，并响应到前端
        CaptchaVo captchaVo = new CaptchaVo(img, key);
        return captchaVo;
    }

    @Override
    public String login(LoginVo loginVo) {
        //校验是否输入了验证码
        if (!StringUtils.hasText(loginVo.getCaptchaCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //校验验证码信息
        String code = redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (code == null) {//验证码过期
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if (!code.equals(loginVo.getCaptchaCode().toLowerCase())) { //验证码错误
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //验证用户
        SystemUser user = service.getOne(new LambdaQueryWrapper<SystemUser>()
                .eq(SystemUser::getUsername, loginVo.getUsername()));
        if (user == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //验证用户状态
        if (user.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //验证密码
        String md5Password = DigestUtils.md5DigestAsHex(loginVo.getPassword().getBytes());
        if (!user.getPassword().equals(md5Password)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        return JWTUtil.createToken(user.getId(), user.getName());
    }

    @Override
    public SystemUserInfoVo info() {
        LoginUser loginUser = LoginUserContext.getLoginUser();
        SystemUser systemUser = service.getById(loginUser.getUserId());

        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        systemUserInfoVo.setName(systemUser.getName());
        return systemUserInfoVo;
    }
}
